from typing import Optional

from sqlalchemy.orm import Session

from app.models.member import MemberDo


def get_member_by_id(db: Session, user_id: int) -> Optional[MemberDo]:
    """通过用户id获取用户"""
    return db.query(MemberDo).filter(MemberDo.id == user_id).first()


def get_member_by_phone(db: Session, phone: str) -> Optional[MemberDo]:
    """通过手机号获取用户"""
    return db.query(MemberDo).filter(MemberDo.mobile == phone).first()


def register_member(db: Session, nick_name: str, phone: str,
                    platform: str) -> MemberDo:
    """注册会员"""
    member_db = get_member_by_phone(db, phone)
    if member_db:
        # 修改
        member_db.nick_name = nick_name
        member_db.mobile = phone
        member_db.platform = platform
        db.commit()
        db.refresh(member_db)
        return member_db
    # 保存会员信息
    db_user = MemberDo(nick_name=nick_name,
                       phone=phone,
                       gender="未知",
                       platform=platform,
                       country='中国',
                       balance=0,
                       points=0,
                       pay_money=0,
                       expend_money=0)
    db.add(db_user)
    db.commit()
    db.refresh(member_db)
    return member_db
